<template>
  <div class="user-table-page">
    <!-- 顶部"新增用户"按钮 -->
    <div class="top-view">
      <span class="data-storage">数据存储</span>
      <button class="add-user-btn btn-base btn-primary" @click="handleAddUser">新增用户</button>
    </div>


    <!-- 调用自定义表格组件 -->
    <ElTable :data="currentPageData" :columns="tableColumnsRef" show-selection show-action show-pagination
      :pagination="paginationRef" @selection-change="handleSelect" @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <!-- 姓名列：自定义头像 + 文字 -->
      <template #name="{ row }">
        <div class="name-cell">
          <img :src="row.avatar" alt="用户头像" class="avatar" />
          <span>{{ row.name }}</span>
        </div>
      </template>

      <!-- 状态列 -->
      <template #status="{ row }">
        <span class="status-text">{{ row.status }}</span>
      </template>
      <template #action="{ row }">
        <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
        <el-button size="small" type="danger" plain @click="handleDelete(row)">删除</el-button>
      </template>
    </ElTable>

    <!-- 用户新增/编辑弹窗 -->
    <UserModal
      :visible="modalVisible"
      :user-data="currentUser"
      @update:visible="modalVisible = $event"
      @confirm="handleModalConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 1. 导入自定义表格组件
import ElTable from '@/components/Table/ElTable.vue';
// 2. 导入弹窗组件
import UserModal from './UserModal.vue';
// 3. 从抽离的 JS 文件中导入数据和方法
import { tableColumns as originTableColumns, initPagination, fetchUserList } from '../index';
import { createUser, updateUser, deleteUser } from '@/api/users';

const userListRef = ref([]);
const tableColumnsRef = ref(originTableColumns);
const paginationRef = ref({ ...initPagination });

// 弹窗相关
const modalVisible = ref(false);
const currentUser = ref({});

// 计算当前页数据
const currentPageData = computed(() => {
  // 这里我们不再使用分页逻辑，因为后端已经处理了分页
  return userListRef.value;
});

// 获取用户列表数据
const loadUserList = async () => {
  const data = await fetchUserList(paginationRef.value.currentPage, paginationRef.value.pageSize);
  if (data) {
    userListRef.value = data.list;
    paginationRef.value.total = data.pagination.total;
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadUserList();
});

// 勾选事件
const handleSelect = (selectedRows) => {
  console.log('勾选的行：', selectedRows);
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  paginationRef.value.pageSize = val;
  paginationRef.value.currentPage = 1; // 重置到第一页
  loadUserList(); // 重新加载数据
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  paginationRef.value.currentPage = val;
  loadUserList(); // 重新加载数据
};

// 新增用户
const handleAddUser = () => {
  currentUser.value = {};
  modalVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  currentUser.value = { ...row };
  modalVisible.value = true;
};

// 处理弹窗确认
const handleModalConfirm = async (formData) => {
  try {
    let response;

    if (formData.id) {
      // 编辑用户
      response = await updateUser(formData.id, formData);
    } else {
      // 新增用户
      response = await createUser(formData);
    }

    if (response.code === 200 || response.code === 201) {
      ElMessage.success(formData.id ? '用户更新成功' : '用户新增成功');
      modalVisible.value = false;
      loadUserList(); // 重新加载数据
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message);
  }
};

// 删除事件
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteUser(row.id);
    if (response.code === 200) {
      ElMessage.success('用户删除成功');
      loadUserList(); // 重新加载数据
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};
</script>
<style scoped lang="scss">
.user-table-page {
  padding: 20px;

  .add-user-btn {
    margin-bottom: 5px;
  }

  .name-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
    }
  }

  .status-text {
    color: #409eff;

  }

  .top-view {
    background-color: rgb(253, 253, 251);
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .data-storage {
      color: rgb(167, 175, 178);
    }
  }

  .el-table {
    .el-button {
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .el-pagination {
    margin-top: 20px;

    .el-pager {
      li {
        min-width: 32px;
        height: 32px;
        line-height: 32px;
      }
    }
  }
}
</style>
